Maps = {

	map : null,

	home : null,
	
	markers: [],

	directionsDisplay : null,

	directionsService : null,
	
	geocoder: null,

	initialize : function() {
		Maps.geocoder = new google.maps.Geocoder();
		Maps.directionsService = new google.maps.DirectionsService();
		var rendererOptions = {
				  draggable: true
				};
		Maps.directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
		var myLatlng = new google.maps.LatLng(39.011902, -98.48424649999998);
		var mapDiv = document.getElementById('map_canvas');
		var myOptions = {
			zoom : 4,
			center : myLatlng,
			mapTypeId : google.maps.MapTypeId.ROADMAP,
			icon: "/img/icons/pin.png"
		}
		Maps.map = new google.maps.Map(mapDiv, myOptions);
	},
    
	buildMap: function(data)
	{
		for(var i in Maps.markers)
			Maps.markers[i].setVisible(false);
		
		Maps.directionsDisplay.setMap(Maps.map);

		if(data.start && data.end)
	    {
		
			var request = {
				origin : data.start,
				waypoints: data.waypoints,
				destination : data.end,
				travelMode : google.maps.TravelMode.DRIVING
			};
			Maps.directionsService.route(request, function(result, status) {
				if (status == google.maps.DirectionsStatus.OK) {
					Maps.directionsDisplay.setDirections(result);
				}
			});
		
	    }
		else 
		{
			Maps.directionsDisplay.setDirections({routes:[]});
			if(data.start)
		    {
				Maps.geocoder.geocode({address:data.start}, function(results, status)
	            {
					if (status == google.maps.GeocoderStatus.OK) {
					  Maps.map.setCenter(results[0].geometry.location);
				      Maps.createMarker(results[0].geometry.location);
					}
			    });
				Maps.map.setZoom(6);
		    }
			else
			{
				Maps.initialize();
			}
		}
		
	},
	
	buildGeoLocationMarker: function(data){
		var marker;
		Maps.geocoder.geocode({address:data.name}, function(results, status)
        {
			if (status == google.maps.GeocoderStatus.OK) {
			  Maps.map.setCenter(results[0].geometry.location);
		      marker = Maps.createMarker(results[0].geometry.location);
		      
		      var infoWindow = new google.maps.InfoWindow({
					content:data.content
				});
				google.maps.event.addListener(marker, 'click', function() {
					infoWindow.open(Maps.map, marker);
				  });
			}
	    });
	},
	
	
	
	createMarkers: function(list){
		for(i in list)
		{
			Maps.buildGeoLocationMarker(list[i]);
		}
	},
	
	createMarker: function(location){
		var marker = new google.maps.Marker({
            map: Maps.map,
            position: location,
			icon: "/img/icons/pin.png"
        });
		Maps.markers.push(marker);
		return marker;
	}
}
$(function() {
	Maps.initialize();
});
